package com.yange.accountbook.ui

import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import androidx.recyclerview.widget.LinearLayoutManager
import com.yange.accountbook.databinding.AccountDetailActivityBinding
import com.yange.accountbook.entity.AccountDetailEntity
import com.yange.accountbook.entity.AccountEntity
import com.yange.accountbook.events.AccountDetailChangeEvent
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.ui.adapter.DetailListOneAdapter
import com.yange.accountbook.utils.StringUtils
import com.yange.accountbook.utils.UserDao
import com.yange.accountbook.utils.showToast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

class AccountDetailActivity : BaseActivity<AccountDetailActivityBinding>() {


    var year = 2022
    var month = 11
    var day = 1

    private lateinit var dialog: DatePickerDialog
    lateinit var oneAdapter: DetailListOneAdapter
    lateinit var account: AccountEntity

    override fun getViewBinding() = AccountDetailActivityBinding.inflate(layoutInflater)

    override fun init() {
        account = intent.getParcelableExtra("account")!!

        oneAdapter = DetailListOneAdapter()
        binding.dataList.layoutManager = LinearLayoutManager(this)
        binding.dataList.adapter = oneAdapter

        initView()
        initListener()
    }

    private fun initView() {
        buildTitleBar()
        initDate()
        getDataList()
    }

    private fun refreshView() {
        refreshAccount()
        getDataList()
    }
    private fun initDate(){
        val calendar: Calendar = Calendar.getInstance()
        buildDate(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
    }

    private fun buildDate( year1:Int, month1:Int, day1: Int){

        month = month1
        year = year1
        day = day1
        if (UserDao.getUserInfo().periodStatus && day1 < UserDao.getUserInfo().periodDay){
            month = month1 -1
            if (month < 0){
                month = 11
                year = year1 -1
            }
        }
        binding.tvYear.text = year.toString() + "年"
        binding.tvMouth.text = (month+1).toString() + "月"
    }



    private fun buildTitleBar() {
        binding.titleBar.setTitle(StringUtils.buildMoneyTitleBar(account.name, account.money))
    }


    private fun initListener() {
        //明细变更事件
        EventBus.getDefault().register(this)

        binding.smartRefresh.setOnRefreshListener {
            getDataList()
        }
        //新增明细
        binding.titleBar.tvForward?.setOnClickListener {
            AddItemActivity.startByAccount(this,account)
        }

        binding.layoutDate.setOnClickListener {
            dialog = DatePickerDialog(
                this,
                { p0, year1, month1, day1 ->
                    buildDate(year1, month1, day1)
                    getDataList()
                },
                year,
                    month,
                    day
                )

            dialog.show()

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAccountDetailChange(event: AccountDetailChangeEvent) {
        refreshView()
    }
    private fun getDataList() {

        RetrofitClient.getInstance().invokePostBody(
            this, Api.ACCOUNT_RECORD_LIST, mapOf(
                "accountId" to account.id,
                "year" to year,
                "mon" to (month+1)
            )
        ).subscribe(object : RecObserver<BaseResponse<AccountDetailEntity>>(this, false, false) {
            override fun onSuccess(t: BaseResponse<AccountDetailEntity>?) {

                binding.tvOut.text = "￥" + StringUtils.getNoMoreThanTwoDigits(t?.data?.outMoney!!)
                binding.tvIn.text = "￥" + StringUtils.getNoMoreThanTwoDigits(t?.data?.inMoney!!)
                binding.smartRefresh.finishRefresh()
                binding.smartRefresh.finishLoadMore()
                oneAdapter.setNewInstance(t?.data?.days)

            }

            override fun onFail(msg: String, code: Int) {
                binding.smartRefresh.finishRefresh()
                binding.smartRefresh.finishLoadMore()
                showToast(msg)
            }
        })
    }


    private fun refreshAccount() {
        RetrofitClient.getInstance().invokeGetAccountInfo(this, account.id)
            .subscribe(object : RecObserver<BaseResponse<AccountEntity>>(this, true, false) {
                override fun onSuccess(t: BaseResponse<AccountEntity>?) {
                    account = t?.data!!
                    buildTitleBar()
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }

            })
    }

    companion object {
        fun start(context: Context, account: AccountEntity) {
            var intent = Intent(context, AccountDetailActivity().javaClass)
            intent.putExtra("account", account)
            context.startActivity(intent)
        }

    }

}